<?php

namespace app\admin\model\yungift;


use addons\yungift\controller\Gift;
use think\Db;

/**
 * 礼品 - 主模型
 */
class GiftMain extends \addons\yungift\model\GiftMain
{
    // 自定义初始化
    protected static function init()
    {
        GiftMain::event('before_write', function ($record) {
            if (array_key_exists('scenario', $record->data)) {
                $specs = json_decode($record['specs'], true);
                if ($record->multi_spec) {
                    $record->worth = min(collection($specs)->column('worth'));
                    $record->amount = min(collection($specs)->column('amount'));
                }
            }
        });

        GiftMain::event('after_write', function ($record) {
            if (array_key_exists('scenario', $record->data)) {
                $specs = json_decode($record['specs'], true);
                if (! $record->multi_spec) {
                    $specs = [];
                }

                // 现有规格
                $existIds = GiftSpec::where(['gift_id' => $record->id])->column('id');

                // 新增和更新规格
                $saveIds = [];
                if ($specs) {
                    foreach ($specs as $spec) {
                        if (empty($spec['id'])) {
                            $giftSpec = new GiftSpec();
                            $giftSpec->scenario = 'batch';
                            $giftSpec->gift_id = $record->id;
                        } else {
                            if (! $giftSpec = GiftSpec::get($spec['id'])) {
                                continue;
                            }
                            $giftSpec->scenario = 'batch';
                        }
                        $giftSpec['type'] = $record['type'];
                        $giftSpec['name'] = $spec['name'];
                        $giftSpec->worth = $spec['worth'];
                        $giftSpec->amount = $spec['amount'];
                        if ($record['type'] == self::TYPE_1) {
                            $giftSpec->count_left = $spec['count_left'];
                        }
                        $giftSpec->allowField(true)->save();
                        $saveIds[] = $giftSpec->id;
                    }
                }

                // 删除规格
                if ($existIds) {
                    if ($deleteIds = array_diff($existIds, $saveIds)) {
                        GiftSpec::destroy($deleteIds);
                        GiftCode::where('gift_spec_id', 'in', $deleteIds)->delete();
                    }
                }

                // 更新无规格库存，其他库存又规格触发
                if ($record['type'] == self::TYPE_2) {
                    if ($record->multi_spec) {
                        GiftCode::where(['gift_id' => $record->id, 'gift_spec_id' => 0])->delete();  // 删除无规格
                    } else {
                        Db::transaction(function () use ($record) {
                            GiftMain::where('id', $record->id)->lock(true)->find();  // 锁住礼品库存
                            $countLeft = GiftCode::where([
                                'gift_id'      => $record->id,
                                'gift_spec_id' => 0,
                                'status'       => GiftCode::STATUS_NORMAL
                            ])->count();
                            GiftMain::update(['count_left' => $countLeft], ['id' => $record->id]);
                        });
                    }
                }
            }

            return true;
        });
    }

    // 封面图 - 覆盖父类
    public function getCoverUrlAttr($value, $data)
    {
        return $value;
    }
}
